const axios = require("axios").default;
const randomnumber = require("random-number");
const cookie = require("cookie");
const qs = require("querystring");
const my_user_agent = require("./user-agent");
const Queue = require("promise-queue");
let queue = new Queue(1, Infinity);
queue.push = queue.add;

let east_cookie = null;

function getNewCookie() {
    let user_agent = my_user_agent.getUserAgent();
    return new Promise(async (resolve, reject) => {
        // let first_access = await axios.get("https://mp.eastday.com", {
        //     headers: {
        //         "User-Agent": user_agent
        //     }
        // });
        // //发现原来不需要第一次access...
        // try {
        //     let login_access = await axios.post("https://mp.eastday.com/login", qs.stringify({
        //         mobile: "18390921465",
        //         password: "east*65huji",
        //         authcode: "",
        //         freelogin: 30
        //     }), {
        //             headers: {
        //                 "User-Agent": user_agent
        //             }
        //         });
        //     let JSESSIONID = cookie.parse(login_access.headers['set-cookie'][0])['JSESSIONID'];
        //     resolve(cookie.serialize("JSESSIONID", JSESSIONID));
        // }catch(err){
        //     console.error("getNewCookie() Failed!"+err);
        //     reject(err);
        // }
        resolve(cookie.serialize("sid", "aff7158a-42b2-4dfb-ac36-dbbcaa321e10"))

    })
}

/**
 * 
 * @param {String} eastday_cookie 
 */
function verifyCookie(eastday_cookie) {
    return new Promise(async (resolve) => {
        let access = await axios.get("http://mp.eastday.com/typeregist.html", {
            headers: {
                cookie: east_cookie,
                "User-Agent": my_user_agent.getUserAgent()
            }
        }).catch(e => {
            resolve(false);
        });
        if (access.status == 200) {
            resolve(true);
        } else {
            resolve(false);
        }
    })
}

function getCookieInner() {
    return new Promise(async resolve => {
        if (east_cookie) {
            let valid = await verifyCookie(east_cookie);
            if (valid) {
                return resolve(east_cookie);
            }
        }
        let new_cookie = await getNewCookie();
        east_cookie = new_cookie;
        resolve(east_cookie);
    })
}

function getCookie() {
    return new Promise(resolve => {
        queue.push(() => {
            return new Promise(async next => {
                let geted_cookie = await getCookieInner();
                resolve(geted_cookie);
                setTimeout($ => next(), 1);
            })
        })
    })
}



if (!module.parent) {
    getNewCookie().then(cookie => console.log(cookie));
}

module.exports = {
    getNewCookie: getNewCookie,
    getCookie: getCookie
}